/*************************************************************************
 * File Name:    Insertion_Sort_List.cc
 * Author:       zero91
 * Mail:         jianzhang9102@gmail.com
 * Created Time: 2013/11/18 10:05:26
 * 
 * Description:  
 |------------------------------------------------------------------------
 | Problem: Insertion Sort List
 | Sort a linked list using insertion sort.
 |------------------------------------------------------------------------
 ************************************************************************/

#include <iostream>
#include <fstream>
#include <sstream>
#include <algorithm>
#include <vector>
#include <queue>
#include <stack>
#include <deque>
#include <map>
#include <set>
#include <functional>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cctype>
#include <cmath>

using namespace std;

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode *insertionSortList(ListNode *head)
    {
        if (head == NULL) return head;
        
        ListNode *ans_head, *ans_tail;
        ListNode *p, *t;
        
        ans_head = ans_tail = head;
        
        /* tail point to the last element of subsorted list, tail->next is begining of unsorted list*/
        for (head = head->next; head != NULL; head = ans_tail->next) {
            if (ans_head->val >= head->val) {
                ans_tail->next = head->next;
                head->next = ans_head;
                ans_head = head;
            } else {
                for (p = ans_head; p != ans_tail; p = p->next) {
                    if (p->next->val > head->val) break;
                }
                if (p != ans_tail) {
                    ans_tail->next = head->next;
                    head->next = p->next;
                    p->next = head;
                } else {
                    ans_tail = ans_tail->next;
                }
            }
        }
        return ans_head;
    }
};

